const jwt = require('jsonwebtoken');
const { uuid } = require('../config/config.default');
const { promisify } = require('util');
const toJwt = promisify(jwt.sign);
const verify = promisify(jwt.verify);
module.exports.createToken = async (userinfo) => {
    const token = await toJwt({ userinfo }, uuid, {
        expiresIn: 7 * 24 * 60 * 60
    });
    return token;
};

// 验证token，写成路由中间件的形式
module.exports.verifyToken = function (required = true) {
    return async (req, res, next) => {
        const authorization = req.headers.authorization;
        const token = authorization ? authorization.split('Bearer ')[1] : null;
        if (token) {
            try {
                let userinfo = await verify(token, uuid);
                req.user = userinfo;
                next();
            } catch (error) {
                res.status(402).json({ error: 'token验证失败' });
            }
        } else if (required) {
            return res.status(402).json({ error: '请传入token' });
        } else {
            next();
        }
    };
};
